package com.joysuch.wwyt.core.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.api.alarmbluetooth.exception.BizException;
import com.joysuch.wwyt.common.entity.CommonVersion;
import com.joysuch.wwyt.common.service.CommonVersionService;
import com.joysuch.wwyt.core.entity.BaseModuleMenuMapping;
import com.joysuch.wwyt.core.mapper.BaseModuleMenuMappingMapper;
import com.joysuch.wwyt.core.service.BaseModuleMenuMappingService;
import com.joysuch.wwyt.licence.exception.LicenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 模块权限映射表 服务实现类
 * </p>
 *
 * @author jialei
 * @since 2022-04-26
 */
@Service
public class BaseModuleMenuMappingServiceImpl extends ServiceImpl<BaseModuleMenuMappingMapper, BaseModuleMenuMapping> implements BaseModuleMenuMappingService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseModuleMenuMappingServiceImpl.class);
    private final CommonVersionService commonVersionService;

    /**
     *
     * @param commonVersionService
     */
    public BaseModuleMenuMappingServiceImpl(CommonVersionService commonVersionService) {
        this.commonVersionService = commonVersionService;
    }

    @Override
    public List<BaseModuleMenuMapping> listValid() throws LicenceException {
        CommonVersion finalVersion = commonVersionService.findLatestVersion("web");
        String md5 = finalVersion.getModuleMd5();
        if (StrUtil.isBlank(md5)) {
            throw new LicenceException(400, "当前版本记录模块md5参数为空");
        }
        List<BaseModuleMenuMapping> moduleMenuMappingList = this.list();
        if (CollectionUtil.isEmpty(moduleMenuMappingList)) {
            throw new LicenceException(400, "获取模块配置信息为空");
        }
        String moduleMD5 = genMD5(moduleMenuMappingList);
        if (!md5.equals(moduleMD5)) {
            LOGGER.debug("com.joysuch.wwyt.core.service.impl.BaseModuleMenuMappingServiceImpl.listValid 原始MD5：{}，计算MD5：{}", md5, moduleMD5);

            throw new LicenceException(400, "模块配置信息被篡改");
        }
        return moduleMenuMappingList;
    }

    @Override
    public String getValidMD5() {
        List<BaseModuleMenuMapping> moduleMenuMappingList = this.list();
        if (CollectionUtil.isEmpty(moduleMenuMappingList)) {
            throw new BizException(400, "获取模块配置信息为空");
        }
        return genMD5(moduleMenuMappingList);
    }

    /**
     * 获取数据 md5 摘要信息
     * @param moduleMenuMappingList
     * @return
     */
    private String genMD5(List<BaseModuleMenuMapping> moduleMenuMappingList) {
        StringBuilder msgBuilder = new StringBuilder("");
        moduleMenuMappingList.sort(Comparator.comparing(BaseModuleMenuMapping::getId));
        for (BaseModuleMenuMapping baseModuleMenuMapping : moduleMenuMappingList) {
            msgBuilder.append(Base64.encode(baseModuleMenuMapping.getModuleCode(), StandardCharsets.UTF_8))
                    .append(baseModuleMenuMapping.getMenuUrl())
                    .append(baseModuleMenuMapping.getDeleteFlag());
        }
        String str = msgBuilder.toString();
        String moduleMd5 = MD5.create().digestHex(str, StandardCharsets.UTF_8);
        return moduleMd5;
    }
}
